package com.zmn.plat.business.impl.msg;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.message.MessageClientIDSetter;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.mcc.dubbo.interfaces.staff.StaffListRemoteService;
import com.zmn.plat.business.interfaces.msg.MsgDingTalkBsService;
import com.zmn.plat.business.interfaces.msg.conf.MsgConfBService;
import com.zmn.plat.common.dictionary.PlatEnum;
import com.zmn.plat.model.entity.channel.Channel;
import com.zmn.plat.model.mq.DingTalkParams;
import com.zmn.plat.model.mq.SendParams;
import com.zmn.plat.model.vo.msg.receive.staff.MsgStaffSimpleVO;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.zmn.common.utils.date.DateUtil.FORMAT_DATETIME;

/**
 * 描述: 发送钉钉消息Service
 *
 * @author jiafei
 * @version 1.0
 * @since 2021/6/21 16:15
 */
@Slf4j
@Service
public class MsgDingTalkBsServiceImpl implements MsgDingTalkBsService {

	@NacosValue(value = "${spring.mq.topic.push}", autoRefreshed = true)
	private String pushTopic;

	@NacosValue(value = "${spring.sendmessage.ruleid}", autoRefreshed = true)
	private Integer ruleId;

	@NacosValue(value = "${spring.sendmessage.dimission.ruleid:0}", autoRefreshed = true)
	private Integer dimissionRuleId;

	@NacosValue(value = "${spring.sendmessage.dimission.dingtaskids:null}", autoRefreshed = true)
	private String dingTalkIdStr;

	@NacosValue(value = "${spring.sendmessage.notifiers}", autoRefreshed = true)
	private List<Integer> notifiers;

	private static final String MQ_TAG = "message_center_system";

	@Resource
	private ZmnMQSender zmnMQSender;

	@Resource
	private MsgConfBService msgConfBService;

	@Resource
	private ChannelService channelService;

	@Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
	private StaffListRemoteService staffListRemoteService;

	@Override
	public void channelCloseSendMessage(List<Integer> channelIds) {

		if (CollectionUtil.isNullOrEmpty(channelIds)) {
			log.error("渠道关闭，发送消息失败，无效的参数，channelIds：{}", channelIds);
			return;
		}
		channelIds.forEach(channelId -> {

			if (Objects.isNull(channelId)) {
				log.error("渠道关闭，发送消息失败，无效的参数，channelId：{}", channelId);
				return;
			}

			Channel channel = channelService.findByKey(channelId);
			if (Objects.isNull(channel) || Objects.equals(channel.getStatus(), GlobalConsts.YES)) {
				log.error("渠道关闭，发送消息失败，无效的渠道，channel：{}", JSON.toJSONString(channel));
				return;
			}

			// 渠道运营/商务 负责人id
			List<Integer> staffIds = Lists.newArrayList();
			staffIds.add(channel.getAbutmenter());
			staffIds.add(channel.getSalesman());

			// 除了渠道的运营和商务人员 外还需要通知的人
			if (CollectionUtil.isNotNullOrEmpty(notifiers)) {
				staffIds.addAll(notifiers);
			}

			// 查询接收消息人的钉钉id
			List<MsgStaffSimpleVO> msgStaffSimpleVOS = msgConfBService.listReceiveStaffSimpleVO(staffIds);
			if (CollectionUtil.isNullOrEmpty(msgStaffSimpleVOS)) {
				log.error("渠道关闭，发送消息失败，未查询到发送人信息，msgStaffSimpleVOS:{}", JSON.toJSONString(msgStaffSimpleVOS));
				return;
			}

			// 拼接dingTalkId
			String dingTalkIdStr = msgStaffSimpleVOS.stream()
													.filter(msgStaff -> StringUtil.isNotBlank(msgStaff.getDTalkId()))
													.map(MsgStaffSimpleVO::getDTalkId)
													.distinct()
													.collect(Collectors.joining(","));

			if (StringUtil.isBlank(dingTalkIdStr)) {
				log.error("渠道关闭，发送消息失败，未查询到发送人钉钉id，dingTalkIdStr:{}", dingTalkIdStr);
				return;
			}

			// 消息内容  生产环境消息系统场景ID：10386，场景名称：消息系统关闭通知
			String msgContent = String.format("渠道ID：%s ；渠道名称：%s；关闭时间：%s", channelId, channel.getName(),
											  DateUtil.dateFormatToString(DateUtil.getNow(), FORMAT_DATETIME));


			// 钉钉消息实例类
			Map<String, String> params = new HashMap<>(2);
			params.put("msg_content", msgContent);
			DingTalkParams dingTalkParams = DingTalkParams.builder()
														  .dingTalkId(dingTalkIdStr)
														  .params(JSON.toJSONString(params))
														  .build();

			// 封装send对象 1402
			SendParams sendParams = SendParams.builder()
											  .ruleId(ruleId).callsName("PLAT")
											  .dingTalkParams(dingTalkParams)
											  .build();

			String serialNumber = MessageClientIDSetter.createUniqID();

			// 序列号
			sendParams.setSerialNumber(serialNumber);
			zmnMQSender.send(pushTopic, MQ_TAG, serialNumber, JSON.toJSONString(sendParams));
			log.info("渠道关闭发送钉钉消息成功,sendParams：{}", JSON.toJSONString(sendParams));
		});
	}

	@Override
	public void dimissionChannelSendMessage(List<Channel> list) throws Exception{
		if(StringUtils.isNotEmpty(dingTalkIdStr) && dimissionRuleId != null && dimissionRuleId > 0) {
			list.stream().filter(Objects::nonNull).parallel().forEach(item -> {
				// 消息内容  测试环境场景ID：10615，线上环境场景ID：10557，场景名称：渠道管理-商务信息缺失钉钉消息
				String msgContent = String.format("渠道所属平台名称：%s ,渠道ID：%s ，渠道名称：%s，商务信息缺失，请渠道管理员填写商务信息",
						PlatEnum.getName(item.getPlat()), item.getChannelId(), item.getName());
				// 钉钉消息实例类
				Map<String, String> params = new HashMap<>(2);
				params.put("msg_content", msgContent);
//				Arrays.stream(dingTalkIdStr.split(",")).forEach(dingId->{
					DingTalkParams dingTalkParams = DingTalkParams.builder()
							.dingTalkId(dingTalkIdStr)
							.params(JSON.toJSONString(params))
							.build();
					// 封装send对象 10557
					SendParams sendParams = SendParams.builder()
							.ruleId(dimissionRuleId).callsName("PLAT")
							.dingTalkParams(dingTalkParams)
							.build();

					String serialNumber = MessageClientIDSetter.createUniqID();

					// 序列号
					sendParams.setSerialNumber(serialNumber);
					zmnMQSender.send(pushTopic, MQ_TAG, serialNumber, JSON.toJSONString(sendParams));
					log.info("渠道关闭发送钉钉消息成功,sendParams：{}", JSON.toJSONString(sendParams));
//				});
			});
		}
	}

}
